# autosave

from PyQt4.QtCore import *
from PyQt4.QtGui import *
from qgis.core import *
from qgis.gui import *

import os
import os.path
import time

import saver
import showform
import resource_rc

class MainPlugin(object):
  def __init__(self, iface):
    # Save a reference to the QGIS iface
    self.iface = iface
    
  def interval(self):
    qt = QSettings().value("AutoSave/interval").toTime()
    nmins = qt.hour()*3600 + qt.minute()*60 + qt.second()
    return nmins

  def nrevisions(self):
    nr = QSettings().value("AutoSave/revisionCount").toInt()[0]
    return nr
    
  def theFolder(self):
    return str(QSettings().value("AutoSave/folder").toString())

  def autosaveEnabled(self):
    return QSettings().value("AutoSave/saveEnabled").toInt()[0] == 2

  def initGui(self):
    """ runs when plugin is activated from the plugin menu """
    # Create action
    self.action = QAction(QIcon(":/icons/hardhat.png"),"Autosave",self.iface.mainWindow())
    self.action.setWhatsThis("Auto Save")
    QObject.connect(QgsProject.instance(), SIGNAL("readProject(const QDomDocument &)"),self.readProject)
    QObject.connect(self.action,SIGNAL("triggered()"),self.showSettings)
    self.iface.addToolBarIcon(self.action)
    self.iface.addPluginToMenu("&AutoSave",self.action)

    QObject.connect(self.iface.mapCanvas(), SIGNAL("renderComplete(QPainter *)"), self.checkSaveMyWork)
    self.last = time.time()

    sb = self.iface.mainWindow().statusBar()
    self.icons = [QIcon(":icons/nohat.png"),QIcon(":icons/hardhat.png")]
    self.messages = ["Autosave disabled","Autosave enabled"]
    self.statusButton = QPushButton(self.icons[1],"",self.iface.mainWindow())
    self.statusButton.setMaximumWidth( 20 )
    self.statusButton.setMaximumHeight( 20 )
    self.setStatusButton()
    sb.addPermanentWidget(self.statusButton)
    QObject.connect(self.statusButton,SIGNAL("clicked()"),self.showSettings)

  def setStatusButton(self):
    s=QSettings()
    v = s.value("AutoSave/saveEnabled").toInt()[0] == 2
    self.statusButton.setToolTip(self.messages[v])
    self.statusButton.setIcon(self.icons[v])

  def readProject(self,dom):
    self.iface.mainWindow().statusBar().showMessage("new project loaded")
    ### TODO ### need to check if this was a previously saved project
    # so that we don't end up creating versions of this...
    
    # if the autosave property is set, prompt for new save name and clear property.
    value,exists = QgsProject.instance().readEntry("AutoSave","isSavedProject")
    if exists:
      QMessageBox.critical(None,"Loaded autosaved project","You have loaded a project that was saved by the auto-save plugin.\nPlease save under a new name.")
      QgsProject.instance().removeEntry("AutoSave","isSavedProject")
      self.iface.actionSaveProjectAs().trigger()
    # restart the time since last saved, since this is a new project
    self.last = time.time()

  def showSettings(self):
    """ show the settings dialog """
    self.ad = showform.AutosaveDialog()
    QObject.connect(self.ad,SIGNAL("accepted()"),self.setStatusButton)
    self.ad.show()

  def checkSaveMyWork(self,painter):
    if not self.autosaveEnabled():
      # saving not enabled
      return
    p = QgsProject.instance()
    dirtState = p.isDirty()
    timeSince = time.time() - self.last
    if timeSince > self.interval():
      self.iface.mainWindow().statusBar().showMessage("Autosaving...")
      self.last = time.time()
      newFileName,fails = saver.saveProject(self.theFolder(),self.nrevisions())
      savename = p.fileName()
      p.setFileName(os.path.join(self.theFolder(),newFileName))
      # set a project property to show this is an autobackup
      p.writeEntry("AutoSave","isSavedProject",True)
      try:
        testWriting(p.fileName())
        p.write()
      except:
        QMessageBox.critical(None,"Autosave Failed","There was a problem testing writability of the Autosave folder. Please check it.")
      # reset the property
      p.removeEntry("AutoSave","isSavedProject")
      p.setFileName(savename)
      # restore whatever dirtiness it was before
      p.dirty(dirtState)
      self.iface.mainWindow().statusBar().showMessage("Autosaving... done.")
      if fails:
        print "Error deleting old projects: + "+ ",".join([str(x) for x in fails])

  def unload(self):
    # Remove the plugin
    self.iface.removePluginMenu("&AutoSave",self.action)
    self.iface.removeToolBarIcon(self.action)
    QObject.disconnect(self.iface.mapCanvas(), SIGNAL("renderComplete(QPainter *)"), self.checkSaveMyWork)


def testWriting(path):
  """ this function really only exists to raise exceptions if anything goes wrong"""
  f = file(path,"w")
  f.write("testing")
  f.close()
  import os
  os.unlink(path)

